<template>
  <div class="send-notification-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>发送通知</span>
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="notificationFormRef"
        :model="notificationForm"
        :rules="notificationRules"
        label-width="120px"
        style="max-width: 800px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input
            v-model="notificationForm.title"
            placeholder="请输入通知标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入通知内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知类型" prop="type">
          <el-radio-group v-model="notificationForm.type">
            <el-radio :label="1">系统通知</el-radio>
            <el-radio :label="2">角色通知</el-radio>
            <el-radio :label="3">个人通知</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <el-text type="info" size="small">
              系统通知：重要系统公告；角色通知：发送给特定角色；个人通知：发送给个人
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="接收者类型" prop="receiverType">
          <el-radio-group v-model="notificationForm.receiverType" @change="handleReceiverTypeChange">
            <el-radio :label="1">指定用户</el-radio>
            <el-radio :label="2">指定角色</el-radio>
            <el-radio :label="4">指定组织</el-radio>
            <el-radio :label="3">全部用户</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <el-text type="warning" size="small">
              注意：只能向权重低于您的角色/用户发送通知
            </el-text>
          </div>
        </el-form-item>

        <el-form-item
          v-if="notificationForm.receiverType === 1"
          label="接收用户"
          prop="receiverUserIds"
        >
          <div class="user-selector-container">
            <el-select
              v-model="notificationForm.receiverUserIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户名搜索"
              :remote-method="searchUsers"
              :loading="userSearchLoading"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.username} (${user.nickname || '未设置昵称'})`"
                :value="user.id"
              />
            </el-select>
            <el-button type="primary" @click="showOrgSelector">
              <el-icon><OfficeBuilding /></el-icon>
              从组织选择
            </el-button>
          </div>
          <div class="form-tip">
            <el-text type="info" size="small">
              输入用户名进行搜索，或从组织架构中选择用户
            </el-text>
          </div>
        </el-form-item>

        <el-form-item
          v-if="notificationForm.receiverType === 2"
          label="接收角色"
          prop="receiverRoleIds"
        >
          <el-select
            v-model="notificationForm.receiverRoleIds"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="`${role.roleName} (权重: ${role.weight || 0})`"
              :value="role.id"
              :disabled="role.weight >= currentUserMaxWeight"
            >
              <span>{{ role.roleName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                权重: {{ role.weight || 0 }}
              </span>
            </el-option>
          </el-select>
          <div class="form-tip">
            <el-text type="info" size="small">
              只能选择权重低于您的角色
            </el-text>
          </div>
        </el-form-item>

        <el-form-item v-if="notificationForm.receiverType === 3" label="提示">
          <el-alert
            title="将发送给所有权重低于您的用户"
            type="info"
            :closable="false"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            <el-icon><Promotion /></el-icon>
            发送通知
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 组织用户选择器 -->
    <organization-user-selector
      v-model="showOrgSelectorDialog"
      :selected-user-ids="notificationForm.receiverUserIds"
      @confirm="handleOrgUserConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Back, Promotion, Refresh, OfficeBuilding } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { sendNotification } from '@/api/notification'
import { getAllRoles } from '@/api/role'
import { getUserList } from '@/api/user'
import { useUserStore } from '@/stores/user'
import OrganizationUserSelector from '@/components/OrganizationUserSelector.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const notificationFormRef = ref(null)
const submitLoading = ref(false)
const userSearchLoading = ref(false)
const roleList = ref([])
const userList = ref([])
const currentUserMaxWeight = ref(0)
const showOrgSelectorDialog = ref(false)

// 通知表单
const notificationForm = reactive({
  title: '',
  content: '',
  type: 1,
  receiverType: 3,
  receiverUserIds: [],
  receiverRoleIds: []
})

// 表单验证规则
const notificationRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 2, max: 200, message: '标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 2, max: 2000, message: '内容长度在 2 到 2000 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  receiverType: [
    { required: true, message: '请选择接收者类型', trigger: 'change' }
  ],
  receiverUserIds: [
    {
      validator: (rule, value, callback) => {
        if (notificationForm.receiverType === 1 && (!value || value.length === 0)) {
          callback(new Error('请至少选择一个接收用户'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  receiverRoleIds: [
    {
      validator: (rule, value, callback) => {
        if (notificationForm.receiverType === 2 && (!value || value.length === 0)) {
          callback(new Error('请至少选择一个接收角色'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 加载角色列表
const loadRoles = async () => {
  try {
    const res = await getAllRoles()
    if (res.code === 200) {
      roleList.value = res.data || []
      
      // 获取当前用户的最高权重
      const currentUserRoles = userStore.roles || []
      currentUserMaxWeight.value = Math.max(
        ...currentUserRoles.map(role => role.weight || 0),
        0
      )
    } else {
      ElMessage.error(res.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索用户
const searchUsers = async (query) => {
  if (!query) {
    userList.value = []
    return
  }
  
  userSearchLoading.value = true
  try {
    const res = await getUserList({ username: query, pageNum: 1, pageSize: 20 })
    if (res.code === 200) {
      userList.value = res.data.records || []
    } else {
      ElMessage.error(res.message || '搜索用户失败')
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    userSearchLoading.value = false
  }
}

// 接收者类型改变
const handleReceiverTypeChange = () => {
  notificationForm.receiverUserIds = []
  notificationForm.receiverRoleIds = []
}

// 显示组织选择器
const showOrgSelector = () => {
  showOrgSelectorDialog.value = true
}

// 组织用户选择确认
const handleOrgUserConfirm = (userIds, users) => {
  // 合并已选用户ID，去重
  const existingIds = new Set(notificationForm.receiverUserIds)
  userIds.forEach(id => existingIds.add(id))
  notificationForm.receiverUserIds = Array.from(existingIds)
  
  // 更新用户列表，用于显示
  const existingUserIds = new Set(userList.value.map(u => u.id))
  users.forEach(user => {
    if (!existingUserIds.has(user.userId)) {
      userList.value.push({
        id: user.userId,
        username: user.username,
        nickname: user.nickname
      })
    }
  })
  
  ElMessage.success(`已选择 ${userIds.length} 个用户`)
}

// 提交表单
const handleSubmit = async () => {
  if (!notificationFormRef.value) return
  
  await notificationFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const res = await sendNotification(notificationForm)
        if (res.code === 200) {
          ElMessage.success('通知发送成功')
          router.push('/notification/list')
        } else {
          ElMessage.error(res.message || '发送失败')
        }
      } catch (error) {
        console.error('发送失败:', error)
        ElMessage.error('发送失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const handleReset = () => {
  notificationFormRef.value?.resetFields()
}

// 返回
const handleBack = () => {
  router.back()
}

// 页面加载
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.send-notification-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  margin-top: 8px;
  line-height: 1.5;
}

.user-selector-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

/* 深色模式适配 */
html.dark .form-tip :deep(.el-text) {
  color: var(--el-text-color-regular);
}
</style>

